<template>
  <div class="health-manage">
    <!-- 搜索框 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input
            v-model="searchQuery"
            placeholder="请输入用户ID或体检日期"
            prefix-icon="el-icon-search"
            @keyup.enter.native="fetchData"
        ></el-input>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="fetchData" style="margin-bottom: 20px;">搜索</el-button>
        <el-button @click="resetData" style="margin-bottom: 20px;">重置</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        :header-cell-style="{ background: '#ccc' }"
        border
    >
      <el-table-column
          prop="id"
          label="体检ID"
          width="80"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="userId"
          label="用户ID"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="checkDate"
          label="体检日期"
          width="180"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="height"
          label="身高(cm)"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="weight"
          label="体重(kg)"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="bloodPressureSystolic"
          label="收缩压(mmHg)"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="bloodPressureDiastolic"
          label="舒张压(mmHg)"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="heartRate"
          label="心率(次/分钟)"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="bloodType"
          label="血型"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="bloodGlucose"
          label="血糖(mmol/L)"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="cholesterol"
          label="胆固醇(mmol/L)"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="triglycerides"
          label="甘油三酯(mmol/L)"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="liverFunction"
          label="肝功能"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="kidneyFunction"
          label="肾功能"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="otherFindings"
          label="其他"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="doctorAdvice"
          label="医生建议"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="current"
          label="记录时间"
          width="180"
          align="center"
      ></el-table-column>
      <el-table-column
          label="操作"
          width="160"
          align="center"
          fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="info" size="mini" @click="openDialog('edit', scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="deleteHealth(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>

    <!-- 添加/编辑体检信息的弹出框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-form :model="healthForm" ref="healthForm" label-width="120px" style="padding-right: 100px;">
        <el-form-item label="用户ID" prop="userId" :rules="[{ required: true, message: '用户ID不能为空' }]">
          <el-input v-model="healthForm.userId" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        <el-form-item label="体检日期" prop="checkDate" :rules="[{ required: true, message: '体检日期不能为空' }]">
          <el-date-picker v-model="healthForm.checkDate" type="date" placeholder="请选择体检日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="身高(cm)" prop="height" :rules="[{ required: true, message: '身高不能为空' }]">
          <el-input v-model="healthForm.height" placeholder="请输入身高"></el-input>
        </el-form-item>
        <el-form-item label="体重(kg)" prop="weight" :rules="[{ required: true, message: '体重不能为空' }]">
          <el-input v-model="healthForm.weight" placeholder="请输入体重"></el-input>
        </el-form-item>
        <el-form-item label="收缩压(mmHg)" prop="bloodPressureSystolic"
                      :rules="[{ required: true, message: '收缩压不能为空' }]">
          <el-input v-model="healthForm.bloodPressureSystolic" placeholder="请输入收缩压"></el-input>
        </el-form-item>
        <el-form-item label="舒张压(mmHg)" prop="bloodPressureDiastolic"
                      :rules="[{ required: true, message: '舒张压不能为空' }]">
          <el-input v-model="healthForm.bloodPressureDiastolic" placeholder="请输入舒张压"></el-input>
        </el-form-item>
        <el-form-item label="心率(次/分钟)" prop="heartRate" :rules="[{ required: true, message: '心率不能为空' }]">
          <el-input v-model="healthForm.heartRate" placeholder="请输入心率"></el-input>
        </el-form-item>
        <el-form-item label="血型" prop="bloodType" :rules="[{ required: true, message: '血型不能为空' }]">
          <el-input v-model="healthForm.bloodType" placeholder="请输入血型"></el-input>
        </el-form-item>
        <el-form-item label="血糖(mmol/L)" prop="bloodGlucose" :rules="[{ required: true, message: '血糖不能为空' }]">
          <el-input v-model="healthForm.bloodGlucose" placeholder="请输入血糖"></el-input>
        </el-form-item>
        <el-form-item label="胆固醇(mmol/L)" prop="cholesterol"
                      :rules="[{ required: true, message: '胆固醇不能为空' }]">
          <el-input v-model="healthForm.cholesterol" placeholder="请输入胆固醇"></el-input>
        </el-form-item>
        <el-form-item label="甘油三酯(mmol/L)" prop="triglycerides"
                      :rules="[{ required: true, message: '甘油三酯不能为空' }]">
          <el-input v-model="healthForm.triglycerides" placeholder="请输入甘油三酯"></el-input>
        </el-form-item>
        <el-form-item label="肝功能" prop="liverFunction" :rules="[{ required: true, message: '肝功能不能为空' }]">
          <el-input v-model="healthForm.liverFunction" placeholder="请输入肝功能"></el-input>
        </el-form-item>
        <el-form-item label="肾功能" prop="kidneyFunction" :rules="[{ required: true, message: '肾功能不能为空' }]">
          <el-input v-model="healthForm.kidneyFunction" placeholder="请输入肾功能"></el-input>
        </el-form-item>
        <el-form-item label="其他" prop="otherFindings" :rules="[{ required: true, message: '其他不能为空' }]">
          <el-input v-model="healthForm.otherFindings" placeholder="请输入其他"></el-input>
        </el-form-item>
        <el-form-item label="医生建议" prop="doctorAdvice" :rules="[{ required: true, message: '医生建议不能为空' }]">
          <el-input v-model="healthForm.doctorAdvice" placeholder="请输入医生建议"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHealth">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from "@/api";
import {formatDate} from "@/utils/date";

export default {
  name: "HealthManage",
  data() {
    return {
      searchQuery: "", // 搜索关键词
      tableData: [], // 表格数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      total: 0, // 总条数
      dialogVisible: false, // 弹出框是否显示
      dialogTitle: "", // 弹出框标题
      healthForm: {
        id: null,
        userId: null,
        checkDate: null,
        height: null,
        weight: null,
        bloodPressureSystolic: null,
        bloodPressureDiastolic: null,
        heartRate: null,
        bloodType: null,
        bloodGlucose: null,
        cholesterol: null,
        triglycerides: null,
        liverFunction: null,
        kidneyFunction: null,
        otherFindings: null,
        doctorAdvice: null,
        current: null
      }, // 体检信息表单数据
      currentAction: "" // 当前操作类型（add/edit）
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    formatDate,
    resetData() {
      this.searchQuery = '';
      this.fetchData();
    },
    // 获取数据
    async fetchData() {
      // 模拟从后端获取数据
      const response = await api.health.healthList();
      const mockData = response.data.data;
      // 根据搜索关键词过滤数据
      let filteredData = mockData.filter((item) =>
          item.userId.toString().includes(this.searchQuery) || formatDate(item.checkDate, 'YYYY-MM-DD').includes(this.searchQuery)
      );

      // 分页处理
      this.total = filteredData.length;
      this.tableData = filteredData.slice(
          (this.currentPage - 1) * this.pageSize,
          this.currentPage * this.pageSize
      );
    },
    // 每页显示条数改变时触发
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    // 当前页码改变时触发
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    // 打开弹出框
    openDialog(action, row = null) {
      this.currentAction = action;
      if (action === "add") {
        this.dialogTitle = "添加体检信息";
        this.healthForm = {
          id: null,
          userId: null,
          checkDate: null,
          height: null,
          weight: null,
          bloodPressureSystolic: null,
          bloodPressureDiastolic: null,
          heartRate: null,
          bloodType: null,
          bloodGlucose: null,
          cholesterol: null,
          triglycerides: null,
          liverFunction: null,
          kidneyFunction: null,
          otherFindings: null,
          doctorAdvice: null,
          current: null
        };
      } else if (action === "edit") {
        this.dialogTitle = "编辑体检信息";
        this.healthForm = {...row};
      }
      this.dialogVisible = true;
    },
    // 保存体检信息
    saveHealth() {
      this.$refs.healthForm.validate((valid) => {
        if (valid) {
          if (this.currentAction === "add") {
            // 添加体检信息逻辑
            api.health.healthAppend(this.healthForm).then(r => {
              if (r.data.code === 200) {
                this.fetchData();
                this.$message.success('添加成功');
              }
            });
          } else if (this.currentAction === "edit") {
            // 编辑体检信息逻辑
            api.health.healthEditor(this.healthForm).then(r => {
              if (r.data.code === 200) {
                this.fetchData();
                this.$message.success('编辑成功');
              }
            });
          }
          this.dialogVisible = false;
        }
      });
    },
    // 删除体检信息
    deleteHealth(row) {
      this.$confirm("确定要删除该体检信息吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除体检信息逻辑
        api.health.healthDelete(row.id).then(r => {
          if (r.data.code === 200) {
            this.$message.success('删除成功！');
            this.fetchData();
          }
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
};
</script>

<style scoped>
.health-manage {
  padding: 20px;
}
</style>